package cn.hnu.qq.client.panel;

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import org.apache.log4j.Logger;

import cn.hnu.qq.client.controller.CrowdController;
import cn.hnu.qq.client.controller.ListenServerMessageThread;
import cn.hnu.qq.client.event.MessageEvent;
import cn.hnu.qq.client.listener.MessageListener;
import cn.hnu.qq.entity.Crowd;
import cn.hnu.qq.entity.User;
import cn.hnu.qq.entity.message.CrowdChartMessage;
import cn.hnu.qq.entity.message.CrowdInfoMessage;
import cn.hnu.qq.entity.message.Message;
import cn.hnu.qq.global.CellRenderer;
import cn.hnu.qq.global.MessageType;
import javax.swing.ImageIcon;

public class CrowdChartPanel extends JPanel implements ActionListener,
		MessageListener {

	private Crowd crowd;

	private JList list;

	private JTextArea textArea; // read

	private JTextArea textArea_1; // write

	private CrowdController controller = CrowdController.getInstance();

	/**
	 * Create the panel.
	 */
	public CrowdChartPanel() {
		setLayout(null);

		JPanel panel = new JPanel();
		panel.setBounds(10, 10, 391, 203);
		add(panel);
		panel.setLayout(null);

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(0, 0, 391, 203);
		panel.add(scrollPane);

		textArea = new JTextArea();
		scrollPane.setViewportView(textArea);
		textArea.setEditable(false);
		textArea.setLineWrap(true);
		JPanel panel_1 = new JPanel();
		panel_1.setBounds(412, 10, 168, 427);
		add(panel_1);
		panel_1.setLayout(null);

		JPanel panel_5 = new JPanel(){
			@Override
			protected void paintComponent(Graphics g) {
				Image image = null;
				try {
					image = ImageIO.read(new File("src/main/java/image/02.jpg"));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				};
						
				g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), this);

			}
		};
		panel_5.setBounds(10, 10, 148, 115);
		panel_1.add(panel_5);

		JLabel lblImage = new JLabel("");
		lblImage.setIcon(new ImageIcon(CrowdChartPanel.class.getResource("/image/xiaohui3.png")));
		panel_5.add(lblImage);

		JPanel panel_6 = new JPanel(){
			@Override
			protected void paintComponent(Graphics g) {
				Image image = null;
				try {
					image = ImageIO.read(new File("src/main/java/image/02.jpg"));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				};
						
				g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), this);

			}
		};
		panel_6.setBounds(10, 129, 148, 288);
		panel_1.add(panel_6);
		panel_6.setLayout(null);

		JScrollPane scrollPane_2 = new JScrollPane();
		scrollPane_2.setBounds(10, 10, 128, 268);
		panel_6.add(scrollPane_2);

		list = new JList();
		list.setCellRenderer(new CellRenderer());
		scrollPane_2.setViewportView(list);

		JPanel panel_2 = new JPanel(){
			@Override
			protected void paintComponent(Graphics g) {
				Image image = null;
				try {
					image = ImageIO.read(new File("src/main/java/image/02.jpg"));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				};
						
				g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), this);

			}
		};
		panel_2.setBounds(10, 223, 391, 214);
		add(panel_2);
		panel_2.setLayout(new BorderLayout(0, 0));

		JPanel panel_3 = new JPanel(){
			@Override
			protected void paintComponent(Graphics g) {
				Image image = null;
				try {
					image = ImageIO.read(new File("src/main/java/image/02.jpg"));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				};
						
				g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), this);

			}
		};
		panel_2.add(panel_3, BorderLayout.SOUTH);

		JButton btnNewButton = new JButton("send");
		panel_3.add(btnNewButton);
		btnNewButton.addActionListener(this);
		JButton btnNewButton_1 = new JButton("save");
		panel_3.add(btnNewButton_1);
		btnNewButton_1.addActionListener(this);
		JButton btnNewButton_2 = new JButton("upload");
		panel_3.add(btnNewButton_2);
		btnNewButton_2.addActionListener(this);
		JButton btnNewButton_3 = new JButton("download");
		panel_3.add(btnNewButton_3);
		btnNewButton_3.addActionListener(this);

		JPanel panel_4 = new JPanel(){
			@Override
			protected void paintComponent(Graphics g) {
				Image image = null;
				try {
					image = ImageIO.read(new File("src/main/java/image/02.jpg"));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				};
						
				g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), this);

			}
		};
		panel_2.add(panel_4, BorderLayout.CENTER);
		panel_4.setLayout(null);

		JScrollPane scrollPane_1 = new JScrollPane();
		scrollPane_1.setBounds(0, 0, 391, 171);
		panel_4.add(scrollPane_1);

		textArea_1 = new JTextArea();
		textArea_1.setLineWrap(true);

		scrollPane_1.setViewportView(textArea_1);
		this.setSize(592, 440);
		ListenServerMessageThread.getInstance().addMessageListener(this);
	}

	//
	@SuppressWarnings("unchecked")
	public void setOwner(Crowd crowd) {
		this.crowd = crowd;
		Set<User> users = crowd.getUsers();
		DefaultListModel<User> dlm = new DefaultListModel<User>();
		for (User u : users) {
			dlm.addElement(u);
		}
		list.setModel(dlm);
		// list.validate();
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getActionCommand().equals("send")) {
			String info = textArea_1.getText();
			try {
				controller.sendMessage(crowd, info);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			textArea_1.setText("");
			info = "【我】" + new SimpleDateFormat("HH-mm-ss").format(new Date())
					+ "\r\n" + info + "\r\n";
			// readAble.insert(info, readAble.getCaretPosition());
			textArea.append(info);
			textArea.setCaretPosition(textArea.getText().length());
		}
		if (e.getActionCommand().equals("save")) {
			String content = textArea.getText();
			String file = controller.getCurUser().getAcount()
					+ "_"
					+ crowd.getCrowdName()
					+ "_"
					+ new SimpleDateFormat("yyyy:MM:DD:HH:mm:ss")
							.format(new Date());
			String dir = "D://chart content";
			File f = new File(dir);
			if (!f.exists()) {
				f.mkdir();
			}
			try {
				DataOutputStream dout = new DataOutputStream(
						new FileOutputStream(new File(dir + "/" + file)));
				dout.writeUTF(content);
				dout.close();
			} catch (Exception e1) {
				JOptionPane.showMessageDialog(this, "记录保存出错，请稍后再试");
				e1.printStackTrace();
			}
			return;
		}
		if (e.getActionCommand().equals("upload")) {
			controller.sendUploadMessage(crowd, textArea.getText());
		}
	}

	public void messageArrived(MessageEvent event) {
		Message ms = event.getSource();
		Logger.getLogger(CrowdChartPanel.class).debug("获取消息  ：" + event);
		if (ms.getMessageType() == MessageType.CROWD_CHART) {
			if (((CrowdChartMessage) ms).getCrowdName().equals(crowd.getCrowdName())) {
				String info = ((CrowdChartMessage) ms).getMes();
				info = "【" + ((CrowdChartMessage) ms).getAccount() + "】"
						+ new SimpleDateFormat("HH-mm-ss").format(new Date())
						+ "\r\n" + info + "\r\n";
				textArea.append(info);
				textArea.setCaretPosition(textArea.getText().length());
			}
		}
		if (ms.getMessageType() == MessageType.CROWD_INFO) {
			CrowdInfoMessage cim = (CrowdInfoMessage) ms;
			
				setOwner(cim.getCrowd());
				System.err.println("1111111111111");
				Map<String, User> users = cim.getUsers();
				Set<User> _users = crowd.getUsers();
				for (User u : _users) {
					User _user = users.get(u.getAcount());
					if (_user != null) {
						u.setIp(_user.getIp());
						u.setUserClientPort(_user.getUserClientPort());
					}
				}
				Logger.getLogger(CrowdChartPanel.class).debug(
						"处理完成对于接收到的查询群组消息 ： ");
		
		}
	}

	public void insertMessage(CrowdChartMessage cm) {
		String info = cm.getMes();
		info = "【" + cm.getAccount() + "】"
				+ new SimpleDateFormat("HH-mm-ss").format(new Date()) + "\r\n"
				+ info + "\r\n";
		textArea.append(info);
		textArea.setCaretPosition(textArea.getText().length());
	}

	public void addNewMember(User user) {
		DefaultListModel<User> model = (DefaultListModel<User>) list.getModel();
		if (!crowd.getUsers().contains(user)) {
			Logger.getLogger(CrowdChartPanel.class).debug(
					"crwod chart panel 添加新成员：" + user);
			crowd.addUser(user);
			model.addElement(user);
		}
	}
	@Override
	protected void paintComponent(Graphics g) {
		Image image = null;
		try {
			image = ImageIO.read(new File("src/main/java/image/02.jpg"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		};
				
		g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), this);

	}
}
